package com.msh.frame.common.aspect;

import com.alibaba.fastjson.JSONObject;
import com.msh.frame.client.define.StringDef;
import java.util.LinkedList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.springframework.core.io.InputStreamSource;

/**
 * 计算运行时间 记录类名，方法名，参数，返回值，该方法运行总数据
 */
@Slf4j
abstract public class AbstractInfoLoggerAspect {

  /**
   * 重写后定义切面
   */
  abstract protected void pointcut();

  @Around("pointcut()")
  public Object around(ProceedingJoinPoint pjd) throws Throwable {
    long start = System.currentTimeMillis();
    Object result = null;
    long total = 0L;
    String methodName = pjd.getSignature().getName();
    String parm = null;
    Object[] args = pjd.getArgs();
    int length = args.length;
    if (length == 1) {
      if(!isSkipArgs(args[0])){
        parm = JSONObject.toJSONString(args);
      }else {
        parm = StringDef.HYPHEN;
      }
    }else if(length > 1){
      Object[] argsTmp = new Object[length];
      for(int i=0; i< length; i++){
        if(!isSkipArgs(args[i])){
          argsTmp[i]= args[i];
        }else {
          argsTmp[i] = StringDef.HYPHEN;
        }
      }
      parm = JSONObject.toJSONString(argsTmp);
    }
    try {
      result = pjd.proceed();
      total = System.currentTimeMillis() - start;
      String resultString = JSONObject.toJSONString(result);
      log.debug("aopLog {} {} {} {} {}", pjd.getTarget().getClass(), methodName, parm, resultString,
          total);
    } catch (Throwable e) {
      total = System.currentTimeMillis() - start;
      log.warn("aopLog error: {}. {} {} {} {}", e.getMessage(), pjd.getTarget().getClass(), methodName, parm,
          total);
      throw e;
    }

    return result;
  }

  protected boolean isSkipArgs(Object args){
    return args instanceof InputStreamSource;
  }
}
